#include <engine.h>
#include <qtcore/qmath.h>

GEffect::GEffect(QString name, QGraphicsItem *parent)
    : GObject(name, parent)
{
	m_bSingleShot = false;
	m_pFrame = 0;
}

GEffect::~GEffect()
{
}

int	GEffect::GetTotalFrame()
{
	return m_total_frame;
}

int GEffect::GetCurrentFrame()
{
	return m_current_frame;
}

void GEffect::SetSingleShot(bool shot)
{
	m_bSingleShot = shot;
}

void GEffect::SetImage(QString path, int w, int h)
{
	m_image.load(path);

	m_nFrameWidth = w;
	m_nFrameHeight = h;

	if(m_pFrame == NULL)
		m_pFrame = new QImage(m_nFrameWidth, m_nFrameHeight, m_image.format());
	*m_pFrame = m_image.copy(0, 0, m_nFrameWidth, m_nFrameHeight);
	
	m_current_frame = 0;
	//m_total_frame = m_image.width()*m_image.width()/qPow(m_nFrameSize, 2);
	m_total_frame = (m_image.width()/m_nFrameWidth) * (m_image.height()/m_nFrameHeight);
}

QRectF GEffect::boundingRect() const
{
	if(m_pFrame)
		return QRectF(0,0,m_pFrame->width(),m_pFrame->height());

	return QRectF(0,0,0,0);
}

void GEffect::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
	Q_UNUSED(option)
    Q_UNUSED(widget)

	if(m_pFrame)
	{
		painter->drawImage(0,0,*m_pFrame);
	}
}

void GEffect::NextFrame()
{
	if(m_pFrame == NULL)
		return;

	if(m_current_frame++ > m_total_frame)
	{
		if(m_bSingleShot)
			return;
		
		m_current_frame = 0;
	}
	
	int count_w = m_image.width() / m_nFrameWidth;
	int index_h = m_current_frame / count_w;
	int index_w = m_current_frame % count_w;
	
	*m_pFrame = m_image.copy(index_w*m_nFrameWidth, index_h*m_nFrameHeight, m_nFrameWidth, m_nFrameHeight);
}

void GEffect::SetFrame(int frame)
{
	if(frame == m_current_frame || frame > m_total_frame)
		return;
	
	prepareGeometryChange();
	//qDebug() << "Effect frame" << frame;
	m_current_frame = frame;
		
	int count_w = m_image.width() / m_nFrameWidth;
	int index_h = m_current_frame / count_w;
	int index_w = m_current_frame % count_w;
	
	*m_pFrame = m_image.copy(index_w*m_nFrameWidth, index_h*m_nFrameHeight, m_nFrameWidth, m_nFrameHeight);
	//invalidate();
}

void GEffect::FinishedAnimation(QEvent::Type type, void* param)
{
	if(type == GEvent::Evt_Effect)
	{
		Destroy();
	}
}
